package com.atguigu.gulimall.order.service.impl;

import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.MemberRspVo;
import com.atguigu.gulimall.order.dao.OrderDao;
import com.atguigu.gulimall.order.entity.OrderEntity;
import com.atguigu.gulimall.order.entity.OrderItemEntity;
import com.atguigu.gulimall.order.entity.PaymentInfoEntity;
import com.atguigu.gulimall.order.enume.OrderStatusEnum;
import com.atguigu.gulimall.order.exception.NoStockException;
import com.atguigu.gulimall.order.feign.CartFeignService;
import com.atguigu.gulimall.order.feign.MemberFeignService;
import com.atguigu.gulimall.order.feign.ProductFeignService;
import com.atguigu.gulimall.order.feign.WareFeignService;
import com.atguigu.gulimall.order.interceptor.OrderInterceptor;
import com.atguigu.gulimall.order.service.OrderItemService;
import com.atguigu.gulimall.order.service.OrderService;
import com.atguigu.gulimall.order.service.PaymentInfoService;
import com.atguigu.gulimall.order.to.OrderCreateTo;
import com.atguigu.gulimall.order.to.SpuInfoTo;
import com.atguigu.gulimall.order.vo.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;


@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {

    ThreadLocal<OrderSubmitVo> orderSubmitVoThreadLocal=new ThreadLocal<>();

    @Autowired
    PaymentInfoService paymentInfoService;
    @Autowired
    OrderItemService orderItemService;
    @Autowired
    private ProductFeignService productFeignService;
    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    private MemberFeignService memberFeignService;
    @Autowired
    private CartFeignService cartFeignService;
    @Autowired
    private ThreadPoolExecutor executor;
    @Autowired
    private WareFeignService wareFeignService;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public OrderConfirmVo confirmOrder() throws ExecutionException, InterruptedException {
        OrderConfirmVo orderConfirmVo = new OrderConfirmVo();
        MemberRspVo memberRspVo = OrderInterceptor.threadLocal.get();
        Long memberId = memberRspVo.getId();
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();

        CompletableFuture<Void> addressfuture = CompletableFuture.runAsync(() -> {
            RequestContextHolder.setRequestAttributes(requestAttributes);
            // 获取收货地址
            List<MemberAddressVo> address = memberFeignService.getAddress(memberId);
            orderConfirmVo.setAddress(address);
        }, executor);


        CompletableFuture<Void> cart = CompletableFuture.runAsync(() -> {
            RequestContextHolder.setRequestAttributes(requestAttributes);
            //获取已选中的购物项
            List<OrderItemVo> orderItemVos = cartFeignService.getCheckedCart();
            orderConfirmVo.setOrderItemVos(orderItemVos);
        }, executor).thenRunAsync(()->{
            RequestContextHolder.setRequestAttributes(requestAttributes);
            List<Long> skuIds = orderConfirmVo.getOrderItemVos().stream().map((orderItemVo -> {
                return orderItemVo.getSkuId();
            })).collect(Collectors.toList());
            List<SkuHasStockVo> stockVoBySkuIds = wareFeignService.getSkuHasStockVoBySkuIds(skuIds);
            Map<Long, Boolean> collect = stockVoBySkuIds.stream().collect(Collectors.toMap(SkuHasStockVo::getSkuId, SkuHasStockVo::getHasStock));
            orderConfirmVo.setHasStoke(collect);
        },executor);

        orderConfirmVo.setIntegration(memberRspVo.getIntegration());
        CompletableFuture.allOf(addressfuture,cart).get();
        int count=0;
        for (OrderItemVo orderItemVo : orderConfirmVo.getOrderItemVos()) {
            count=count+orderItemVo.getCount();
            orderConfirmVo.setCount(count);
        }
        String orderToken = UUID.randomUUID().toString().replace("-", "");
        String orderTokenPre="order:token:";
        redisTemplate.opsForValue().set(orderTokenPre+memberId,orderToken);
        orderConfirmVo.setOrderToken(orderToken);
        return orderConfirmVo;
    }

    @Transactional
    @Override
    public SubmitOrderResponseVo submitOrder(OrderSubmitVo orderSubmitVo) {
        orderSubmitVoThreadLocal.set(orderSubmitVo);
        SubmitOrderResponseVo response=new SubmitOrderResponseVo();
        response.setCode(0);
        MemberRspVo memberRspVo = OrderInterceptor.threadLocal.get();
        String orderToken = orderSubmitVo.getOrderToken();
        Long memberId = memberRspVo.getId();
        String script= "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
        Long execute = redisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class), Arrays.asList("order:token:" + memberId), orderToken);
//        0失败 1成功
        if (execute==0L){
            response.setCode(1);
            return response;
        }else {
            //  检验令牌成功
            //  下单：创建订单、检验令牌、检验价格、锁库存
                //创建一个订单
            OrderCreateTo orderCreateTo=createOrderTo();
                //检验价格
            BigDecimal payPrice = orderSubmitVo.getPayPrice();
            BigDecimal payAmount = orderCreateTo.getOrder().getPayAmount();
            if (Math.abs(payAmount.subtract(payPrice).doubleValue()) < 0.01){
                //继续操作
                //保存订单
                saveOrder(orderCreateTo);
//                String exchange, String routingKey, Object message
                rabbitTemplate.convertAndSend("order-event-exchange","order.create.order",orderCreateTo.getOrder());
                //锁定库存，只要有问题就抛异常，回滚订单数据
                WareSkuLockVo wareSkuLockVo = new WareSkuLockVo();
                wareSkuLockVo.setOrderSn(orderCreateTo.getOrder().getOrderSn());
                List<OrderItemVo> collect = orderCreateTo.getOrderItemEntities().stream().map(item -> {
                    OrderItemVo orderItemVo = new OrderItemVo();
                    orderItemVo.setSkuId(item.getSkuId());
                    orderItemVo.setCount(item.getSkuQuantity());
                    return orderItemVo;
                }).collect(Collectors.toList());
                wareSkuLockVo.setLocks(collect);
                R lock = wareFeignService.lock(wareSkuLockVo);
                if (lock.getCode()==0){
                    //锁定成功
                    response.setOrder(orderCreateTo.getOrder());
//                    int i=1/0;

                    return response;
                }else {
                    //锁定失败
                    response.setCode(3);
                    throw new NoStockException(1L);
//                    return response;
                }
            }else {
                //验价失败
                response.setCode(2);
                return response;
            }
        }
    }

    @Override
    public OrderEntity getStatusByOrderSn(String orderSn) {
        OrderEntity order_sn = baseMapper.selectOne(new QueryWrapper<OrderEntity>().eq("order_sn", orderSn));

        return order_sn;
    }

    @Override
    public void releaseOrder(OrderEntity orderEntity) {
//          查看订单状态
        OrderEntity byId = this.getById(orderEntity.getId());
        if (byId.getStatus()==0){
            OrderEntity orderEntity1 = new OrderEntity();
            orderEntity1.setId(orderEntity.getId());
            orderEntity1.setStatus(OrderStatusEnum.CANCLED.getCode());
            this.updateById(orderEntity1);
            String orderSn = byId.getOrderSn();
            rabbitTemplate.convertAndSend("order-event-exchange","order.release.other",orderSn);
        }
    }

    @Override
    public PayVo getPayVo(String orderSn) {
        OrderEntity orderEntity = this.getOne(new QueryWrapper<OrderEntity>().eq("order_sn", orderSn));
        PayVo payVo = new PayVo();
        BigDecimal total = orderEntity.getTotalAmount().setScale(2, BigDecimal.ROUND_UP);
        payVo.setTotal_amount(total.toString());
        payVo.setOut_trade_no(orderSn);
        List<OrderItemEntity> order_sn = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", orderSn));
        OrderItemEntity orderItemEntity = order_sn.get(0);
        payVo.setSubject(orderItemEntity.getSpuName());
        payVo.setBody(orderItemEntity.getSkuName());
        return payVo;
    }

    @Override
    public PageUtils getOrderList(Map<String, Object> param) {
        MemberRspVo memberRspVo = OrderInterceptor.threadLocal.get();
        Long memberId = memberRspVo.getId();
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(param),
                new QueryWrapper<OrderEntity>().eq("member_id",memberId).orderByDesc("id")
        );
        for (OrderEntity orderEntity : page.getRecords()) {
            String orderSn = orderEntity.getOrderSn();
            List<OrderItemEntity> list = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", orderSn).orderByDesc("id"));
            orderEntity.setItemEntitys(list);
        }

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public String handlePayNotify(PayAsyncVo vo) {
        //生成oms_payment_info
        PaymentInfoEntity paymentInfoEntity = new PaymentInfoEntity();
        paymentInfoEntity.setOrderSn(vo.getOut_trade_no());
        paymentInfoEntity.setAlipayTradeNo(vo.getTrade_no());
        paymentInfoEntity.setTotalAmount(vo.getTotal_amount());
        paymentInfoEntity.setCreateTime(vo.getNotify_time());
        paymentInfoEntity.setPaymentStatus(vo.getTrade_status());
        paymentInfoService.save(paymentInfoEntity);

        if (vo.getTrade_status().equals("TRADE_SUCCESS") || vo.getTrade_status().equals("TRADE_FINISHED")){
            //支付成功 修改订单状态
            baseMapper.updateOrderStatus(vo.getOut_trade_no());
        }
        return "success";
    }

    private void saveOrder(OrderCreateTo orderCreateTo) {
        OrderEntity orderEntity = orderCreateTo.getOrder();
        this.save(orderEntity);
        List<OrderItemEntity> orderItemEntities = orderCreateTo.getOrderItemEntities();
        orderItemService.saveBatch(orderItemEntities);
    }

    private OrderCreateTo createOrderTo() {
        OrderCreateTo orderCreateTo = new OrderCreateTo();
        String orderSn = IdWorker.getTimeId();
        //创建订单order
        OrderEntity order=buildOrder(orderSn);
        //创建订单项 orderItem
        List<OrderItemEntity> orderItemEntities=buildOrderItems(orderSn);
        //计算价格和积分
        computePrice(order,orderItemEntities);

        orderCreateTo.setOrder(order);
        orderCreateTo.setOrderItemEntities(orderItemEntities);
        return orderCreateTo;
    }

    private void computePrice(OrderEntity entity, List<OrderItemEntity> orderItemEntities) {
        //总价
        BigDecimal total = BigDecimal.ZERO;
        //优惠价格
        BigDecimal promotion=new BigDecimal("0.0");
        BigDecimal integration=new BigDecimal("0.0");
        BigDecimal coupon=new BigDecimal("0.0");
        //积分
        Integer integrationTotal = 0;
        Integer growthTotal = 0;
        //设置各种总金额 总优惠 总积分
        for (OrderItemEntity orderItemEntity : orderItemEntities) {
            total=total.add(orderItemEntity.getRealAmount());
            promotion=promotion.add(orderItemEntity.getPromotionAmount());
            integration=integration.add(orderItemEntity.getIntegrationAmount());
            coupon=coupon.add(orderItemEntity.getCouponAmount());
            integrationTotal += orderItemEntity.getGiftIntegration();
            growthTotal += orderItemEntity.getGiftGrowth();
        }
        entity.setTotalAmount(total);
        entity.setPromotionAmount(promotion);
        entity.setIntegrationAmount(integration);
        entity.setCouponAmount(coupon);
        entity.setIntegration(integrationTotal);
        entity.setGrowth(growthTotal);
        //付款价格=商品价格+运费
        entity.setPayAmount(entity.getFreightAmount().add(total));

        //设置删除状态(0-未删除，1-已删除)
        entity.setDeleteStatus(0);

    }

    private List<OrderItemEntity> buildOrderItems(String orderSn) {
        //获取到购物车列表
        List<OrderItemVo> checkedCart = cartFeignService.getCheckedCart();
        List<OrderItemEntity> orderItemEntities = checkedCart.stream().map(item -> {
            OrderItemEntity orderItemEntity = new OrderItemEntity();
            orderItemEntity.setOrderSn(orderSn);
            //设置SKU信息
            Long skuId = item.getSkuId();
            orderItemEntity.setSkuId(skuId);
            orderItemEntity.setSkuName(item.getTitle());
            orderItemEntity.setSkuAttrsVals(StringUtils.collectionToDelimitedString(item.getSkuAttr(), ";"));
            orderItemEntity.setSkuPic(item.getImage());
            orderItemEntity.setSkuPrice(item.getPrice());
            orderItemEntity.setSkuQuantity(item.getCount());
            //设置spu信息
            SpuInfoTo spuInfo = productFeignService.getSpuInfoBySkuId(skuId);
            if (spuInfo!=null){
                orderItemEntity.setSpuId(spuInfo.getId());
                orderItemEntity.setSpuName(spuInfo.getSpuName());
                orderItemEntity.setSpuBrand(spuInfo.getBrandName());
                orderItemEntity.setCategoryId(spuInfo.getCatalogId());
            }
            //设置成长积分
            orderItemEntity.setGiftGrowth(item.getPrice().multiply(new BigDecimal(item.getCount())).intValue());
            orderItemEntity.setGiftIntegration(item.getPrice().multiply(new BigDecimal(item.getCount())).intValue());
            //设置价格
            orderItemEntity.setPromotionAmount(BigDecimal.ZERO);
            orderItemEntity.setCouponAmount(BigDecimal.ZERO);
            orderItemEntity.setIntegrationAmount(BigDecimal.ZERO);
//            实际价格
            BigDecimal origin = orderItemEntity.getSkuPrice().multiply(new BigDecimal(orderItemEntity.getSkuQuantity()));
            BigDecimal realPrice = origin.subtract(orderItemEntity.getPromotionAmount())
                    .subtract(orderItemEntity.getCouponAmount())
                    .subtract(orderItemEntity.getIntegrationAmount());
            orderItemEntity.setRealAmount(realPrice);

            return orderItemEntity;
        }).collect(Collectors.toList());
        return orderItemEntities;
    }

    private OrderEntity buildOrder(String orderSn) {
        MemberRspVo memberRspVo = OrderInterceptor.threadLocal.get();
        OrderSubmitVo orderSubmitVo = orderSubmitVoThreadLocal.get();
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderSn(orderSn);
        orderEntity.setMemberId(memberRspVo.getId());
//        获取运费
        FareVo fare = wareFeignService.fare(orderSubmitVo.getAddrId());
        //设置运费
        orderEntity.setFreightAmount(fare.getFare());

        MemberAddressVo address = fare.getMemberAddressVo();
//        设置收货信息
        orderEntity.setReceiverName(address.getName());
        orderEntity.setReceiverPhone(address.getPhone());
        orderEntity.setReceiverPostCode(address.getPostCode());
        orderEntity.setReceiverProvince(address.getProvince());
        orderEntity.setReceiverCity(address.getCity());
        orderEntity.setReceiverRegion(address.getRegion());
        orderEntity.setReceiverDetailAddress(address.getDetailAddress());
        //设置订单状态
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        orderEntity.setConfirmStatus(0);
        orderEntity.setAutoConfirmDay(7);
        return orderEntity;
    }

}